package coop.bancocredicoop.proyectos.gd.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;

import coop.bancocredicoop.proyectos.gd.DocumentTypeForm;
import coop.bancocredicoop.proyectos.gd.FrontEndMessage;
import coop.bancocredicoop.proyectos.gd.domain.DocumentType;
import coop.bancocredicoop.proyectos.gd.query.DataService;

public class TipoDeDocumentoAgregarServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static final String agregarTipoDeDocumento = "/jsp/tiposDeDocumento/agregar.jsp";
	private static final Log log = LogFactory.getLog(TipoDeDocumentoAgregarServlet.class);
	
	@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		DocumentTypeForm documentTypeForm = new DocumentTypeForm();		
		request.setAttribute("documentType", documentTypeForm);
		getServletContext().getRequestDispatcher(agregarTipoDeDocumento).forward(request, response);
		
    }

	@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		// TODO: Validar
		DataService dataService = new DataService();
		FrontEndMessage frontEndMessage = new FrontEndMessage();
		Session session = dataService.getSession();
		DocumentType documentType;
		DocumentTypeForm documentTypeForm;
		
		Transaction tx = session.beginTransaction();
		try {
			documentTypeForm = new DocumentTypeForm();
			documentType = new DocumentType();
			documentTypeForm.fillDocumentTypeWithParameters(documentType, request);
			session.save(documentType);
			tx.commit();
			frontEndMessage.setSuccessMessage("Tipo de documento actualizado");
			log.info(String.format("Tipo de documento agregado satisfactoriamente: %s", documentType.getShortName()));
		} catch (Exception e) {
			String errorMessage = "Error agregando tipo de documento";
			frontEndMessage.addErrorMessage(errorMessage);
			log.error(errorMessage, e);
			dataService.rollback(tx);
		} finally {			
			dataService.closeSession(session);
		}
		
		redirectAfterSuccess(request, response, frontEndMessage);
		
	}

	private void redirectAfterSuccess(HttpServletRequest request,
			HttpServletResponse response, FrontEndMessage frontEndMessage)
			throws IOException {
		frontEndMessage.setMessagesInSession(request);
		response.sendRedirect(request.getContextPath() + "/tiposDeDocumento/lista");
	}
	
}
